#include "cDate_t.h"
#include <time.h>
#include <iostream>
#include <iomanip>
#include <string.h>
using namespace std;

// Initialize static fields
int cDate_t::printFormat = 1;

cDate_t::cDate_t() {
	time_t timeDate;
	struct tm* currentTime;

	timeDate = time(0);
	currentTime = localtime(&timeDate);

	updateDate(currentTime->tm_mday, currentTime->tm_mon + 1,
			currentTime->tm_year + 1900);
}
cDate_t::cDate_t(const int day, const int month, const int year) {
	updateDate(day, month, year);
}

void cDate_t::print() const {
	switch (printFormat) {
	case 1:
		cout << setw(2) << setfill('0') << day << "/" << monthName << "/"
				<< year << endl;
		break;
	case 2:
		cout << setw(2) << setfill('0') << day << "/" << setw(2)
				<< setfill('0') << month << "/" << year << endl;
		break;
	case 3:
		cout << setw(2) << setfill('0') << month << "/" << setw(2)
				<< setfill('0') << day << "/" << year << endl;
		break;
	}
}

int cDate_t::getDay() const {
	return day;
}
int cDate_t::getMonth() const {
	return month;
}
int cDate_t::getYear() const {
	return year;
}
int cDate_t::getDayOfYear() const {
	return dayOfYear;
}
bool cDate_t::isLeap() const {
	return (year % 4 == 0);
}
const char* cDate_t::getDayName() const {
	return dayName;
}
const char* cDate_t::getMonthName() const {
	return monthName;
}

void cDate_t::setDate(const int day, const int month, const int year) {
	updateDate(day, month, year);
}

/* Private Function */

void cDate_t::updateDate(const int day, const int month, const int year) {
	time_t timeDate;
	struct tm* timeInfo;

	timeDate = time(0);
	timeInfo = localtime(&timeDate);

	timeInfo->tm_year = year - 1900;
	timeInfo->tm_mon = month - 1;
	timeInfo->tm_mday = day;

	mktime(timeInfo);

	this->day = timeInfo->tm_mday;
	this->month = timeInfo->tm_mon + 1;
	this->year = timeInfo->tm_year + 1900;
	this->dayOfYear = timeInfo->tm_yday;

	const char * weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
			"Thursday", "Friday", "Saturday" };
	const char * monthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

	strcpy(this->monthName, monthNames[this->month-1]);
	strcpy(this->dayName, weekday[timeInfo->tm_wday]);
}
